package com.dc.ai.config;

import com.dc.ai.model.RedisChatMemory;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Map;

/**
 * Redis 统一配置类
 * 提供Redis序列化和模板配置
 */
@Configuration
public class RedisConfig {

    /**
     * 通用ObjectMapper配置
     * 用于所有Redis序列化场景
     */
    @Bean
    @Primary
    public ObjectMapper messageObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        
        // 禁用所有自动类型推导
        mapper.deactivateDefaultTyping();
        mapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
        
        // 注册自定义反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Message.class, new MessageDeserializer());
        mapper.registerModule(module);
        
        // 允许忽略未知字段
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许空对象
        mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        // 允许单值数组
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        // 允许不带引号的字段名
        mapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        return mapper;
    }

    /**
     * 字符串操作的RedisTemplate
     * 主要用于简单键值对和哈希操作
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(connectionFactory);
        template.setHashValueSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 消息对象的RedisTemplate
     * 专用于Message类型的序列化和反序列化
     */
    @Bean
    public RedisTemplate<String, Message> redisTemplate(
            RedisConnectionFactory factory,
            ObjectMapper redisObjectMapper
    ) {
        RedisTemplate<String, Message> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用Jackson序列化器处理Message对象
        Jackson2JsonRedisSerializer<Message> serializer =
                new Jackson2JsonRedisSerializer<>(Message.class);
        serializer.setObjectMapper(redisObjectMapper);

        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 通用对象的RedisTemplate
     * 用于存储各种Java对象
     */
    @Bean
    public RedisTemplate<String, Object> genericRedisTemplate(
            RedisConnectionFactory factory,
            ObjectMapper redisObjectMapper
    ) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // 使用Jackson序列化器处理通用对象
        Jackson2JsonRedisSerializer<Object> serializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        serializer.setObjectMapper(redisObjectMapper);
        
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        
        return template;
    }

    /**
     * 聊天记忆组件
     */
    @Bean
    public ChatMemory chatMemory(RedisTemplate<String, Message> redisTemplate) {
        return new RedisChatMemory(redisTemplate);
    }

    /**
     * Message类型的Jackson混入配置
     * 用于正确序列化和反序列化不同类型的消息
     */
    @JsonTypeInfo(
            use = JsonTypeInfo.Id.NAME,
            include = JsonTypeInfo.As.PROPERTY,
            property = "messageType",  // 改为使用messageType字段作为类型标识
            visible = true
    )
    @JsonSubTypes({
            @JsonSubTypes.Type(value = UserMessage.class, name = "USER"),
            @JsonSubTypes.Type(value = AssistantMessage.class, name = "ASSISTANT"),
            @JsonSubTypes.Type(value = SystemMessage.class, name = "SYSTEM")
    })
    public abstract class MessageMixIn {
        @JsonCreator
        public MessageMixIn(
                @JsonProperty("text") String content,
                @JsonProperty("metadata") Map<String, Object> metadata
        ) {}

        @JsonProperty("text")
        public abstract String getContent();

        @JsonProperty("role")
        public abstract MessageType getRole();
        
        @JsonProperty("metadata")
        public abstract Map<String, Object> getMetadata();
    }
}